from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from app.schemas.teacher import Teacher, TeacherCreate, TeacherUpdate
from app.crud import teacher as teacher_crud
from app.api.deps import get_db_session

router = APIRouter()

@router.get("/", response_model=List[Teacher])
async def read_teachers(
    skip: int = 0, 
    limit: int = 100, 
    db: AsyncSession = Depends(get_db_session)
):
    teachers = await teacher_crud.get_teachers(db, skip=skip, limit=limit)
    return teachers

@router.post("/", response_model=Teacher, status_code=201)
async def create_teacher(
    teacher: TeacherCreate, 
    db: AsyncSession = Depends(get_db_session)
):
    db_teacher = await teacher_crud.get_teacher_by_email(db, email=teacher.email)
    if db_teacher:
        raise HTTPException(status_code=400, detail="Email already registered")
    return await teacher_crud.create_teacher(db=db, teacher=teacher)

@router.get("/{teacher_id}", response_model=Teacher)
async def read_teacher(
    teacher_id: int, 
    db: AsyncSession = Depends(get_db_session)
):
    db_teacher = await teacher_crud.get_teacher(db, teacher_id=teacher_id)
    if db_teacher is None:
        raise HTTPException(status_code=404, detail="Teacher not found")
    return db_teacher

@router.put("/{teacher_id}", response_model=Teacher)
async def update_teacher(
    teacher_id: int, 
    teacher: TeacherUpdate, 
    db: AsyncSession = Depends(get_db_session)
):
    db_teacher = await teacher_crud.get_teacher(db, teacher_id=teacher_id)
    if db_teacher is None:
        raise HTTPException(status_code=404, detail="Teacher not found")
    
    # 检查邮箱是否已被其他老师使用
    if teacher.email:
        existing_teacher = await teacher_crud.get_teacher_by_email(db, email=teacher.email)
        if existing_teacher and existing_teacher.id != teacher_id:
            raise HTTPException(status_code=400, detail="Email already registered")
    
    return await teacher_crud.update_teacher(db=db, teacher_id=teacher_id, teacher_update=teacher)

@router.delete("/{teacher_id}", response_model=Teacher)
async def delete_teacher(
    teacher_id: int, 
    db: AsyncSession = Depends(get_db_session)
):
    db_teacher = await teacher_crud.get_teacher(db, teacher_id=teacher_id)
    if db_teacher is None:
        raise HTTPException(status_code=404, detail="Teacher not found")
    return await teacher_crud.delete_teacher(db=db, teacher_id=teacher_id)